package com.tjp.eight.ui.fragment.personsetting;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import com.google.gson.Gson;
import com.tjp.eight.R;
import com.tjp.eight.ResultModel;
import com.tjp.eight.RxBus;
import com.tjp.eight.ui.fragment.BaseFragment;
import com.tjp.eight.utils.IsSuccessUtils;
import com.tjp.eight.utils.SharePreferencesUtils;
import com.tjp.eight.utils.StringUtils;
import com.tjp.eight.utils.ToatUtils;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/3/23.
 */
public class FragmentInputCode extends BaseFragment<InputCodePresenter> implements InputCodeView {
    @Bind(R.id.ed_name)
    EditText ed_name;
    private String temp_name = "";

    @Override
    protected InputCodePresenter createPresenter() {
        return new InputCodePresenter(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        contentView = super.onCreateView(inflater, container, savedInstanceState);
        if (contentView == null) {
            contentView = LayoutInflater.from(getContext()).inflate(R.layout.fragment_modify_name, null, false);
        }
        ButterKnife.bind(this, contentView);
        ed_name.setHint("请输入邀请码");
        return contentView;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }

    @OnClick(R.id.tv_submit)
    protected void onSubmit() {
        String new_name = ed_name.getText().toString();
        if (StringUtils.isNullOrEmpty(new_name)) {
            ToatUtils.toastSuccess(getContext(), "请输入邀请码");
            return;
        }
        temp_name = new_name;
        presenter.submitCode(getPJson(new_name));
    }

    private String getPJson(String name) {
        SubmitCodePModel model = new SubmitCodePModel();
        model.inviteCode = name;
        model.uid = SharePreferencesUtils.getUid();
        model.loginkey = SharePreferencesUtils.getLoginKey();
        return new Gson().toJson(model);
    }

    @Override
    public void uploadSuccess(ResultModel model) {
        if (model != null) {
            ToatUtils.toastSuccess(getContext(), model.msg);
            if (IsSuccessUtils.isSuccess(model.result)) {
                RxBus.getInstance().post(new InviteCodeEvent(temp_name));
            }
        }
    }

    @Override
    public void fail(String msg) {

    }
}
